package com.gaeig.repository;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.gaeig.base.ApplicationPersistenceManager;

public class JDORepository implements Repository {

  protected PersistenceManager getPersistenceManager() {
    return ApplicationPersistenceManager.getCurrentPersistenceManager();
  }

  public void delete(Object... objects) {
    PersistenceManager persistenceManager = getPersistenceManager();
    for (Object object : objects) {
      persistenceManager.deletePersistent(object);
    }
  }

  public void save(Object... objects) {
    PersistenceManager persistenceManager = getPersistenceManager();
    for (Object object : objects) {
      persistenceManager.makePersistent(object);
    }
  }

  public void refresh(Object object) {
    getPersistenceManager().refresh(object);
  }

  public <T extends Object> List<T> findAll(Class<T> clazz) {
    return (List<T>) getPersistenceManager().newQuery(clazz).execute();
  }

  public <T> T getObjectById(Object objectId, Class<T> clazz) {
    return (T) getPersistenceManager().getObjectById(objectId);
  }

  public <T> List<T> findByNamedQuery(String queryName, Class<T> clazz) {
    return (List<T>) getPersistenceManager().newQuery(queryName).execute();
  }

  public <T> List<T> findByNamedQuery(String queryName, Class<T> clazz, Object... values) {
    return (List<T>) getPersistenceManager().newQuery(queryName).executeWithArray(values);
  }
}
